const http = require('http');
const querystring = require('querystring');
const uuid = require('uuid');

const session = {};
const cardName = '102139xv19';

http.createServer((req, res) => {
    const cookieObj = querystring.parse(req.headers.cookie, '; ', '=');
    console.log('cookieObj:', cookieObj);
    const cardId = cookieObj[cardName];
    if (cardId && session[cardId]) {
        console.log('访问时session:', session);
        session[cardId].mny -= 10;
        res.end(`current money is ${session[cardId].mny}`);
    } else {
        // 用户第一次访问
        const cardId = uuid.v4();
        session[cardId] = {mny: 100};
        console.log('设置后session:', session);
        res.setHeader(`Set-Cookie`, `${cardName}=${cardId}; httpOnly=true`);
        res.end(`welcome current money 100`);
    }
}).listen(4000);

/*
操作系统会限制一个进程的最大可用内存
nodejs 32位 0.7G
nodejs 65位 1.4G

SO session一般不会放在内存中
一般存在redis中
* */